from django.shortcuts import render

# Create your views here.
from django.shortcuts import render,get_object_or_404
from .models import Post
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
#显示帖子列表的视图

#类视图实现帖子列表的分页机制
from  django.views.generic import ListView
class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'#指定这个列表模型在模板中的参数名称，这是一个上下文变量
    paginate_by = 5#显示三个对象页
    template_name = 'blog/post/list.html'#指定这个列表的模板

from  taggit.models import Tag
def post_list(request,slug_tags=None):#request包含前端所有的请求
    object_list=Post.published.all()#检索已发布的帖子
    tag = None
    if slug_tags:
        tag = get_object_or_404(Tag, slug=slug_tags)
        object_list = object_list.filter(tags__in=[tag])
    paginator=Paginator(object_list,5)#每页3篇
    page=request.GET.get('page')#获取当前页面号
    try:
        posts=paginator.page(page)
    except PageNotAnInteger:
        #所给页面不是整数，提交第一页
        posts=paginator.page(1)#获取所需的页面对象
    except EmptyPage:
        #页面超出范围提交最后一页
        posts=paginator.page(paginator.num_pages)
    return render(request,'blog/post/list.html',{'posts':posts,'page':page, "tag":tag})

#显示独立帖子的
from .froms import CommentForm
from .models import Comment
from django.db.models import Count
def post_detail(request,year,month,day,post):
    #采用get_object_or_404()快捷方式检索期望的帖子，对象不存在，会抛出HTTP404异常
    #检索到会返回，检索到的对象
    post=get_object_or_404(Post,slug=post,
                           status='published',
                           publish__year=year,
                           publish__month=month,
                           publish__day=day)
    # 获取活跃的评论
    comments = post.comments.filter(active=True)
    new_comment = None
    if request.method == 'POST':
        # 实例化帖子
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # 调用save方法创建创建表单所链接的模型实例，并保存到数据库中
            # 如采用commit=False，表示对其加以调用，将会创建模型实例，但不会将其保存到数据库中
            # 需要在保存前进行修改，就十分有用
            new_comment = comment_form.save(commit=False)
            # 将当前帖子设置到创建的评论中
            new_comment.post = post
            # 保存评论到数据库
            new_comment.save()
    else:
        comment_form = CommentForm()
    path = request.path_info
    post_tags_ids = post.tags.values_list('id', flat=True)
    # 获取到的是一个元组，放在一个列表里面，flat=True,会去掉元组括号
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    # 将在每个对象中都添加一个`same_tags`的字段，用来显示标签个数，
    # 对 每个对象都添加 ** 一个 ** 使用查询表达式
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]

    return render(request, 'blog/post/detail.html', {'post': post,
                                                     'comments': comments,
                                                     'new_comment': new_comment,
                                                     'comment_form': comment_form,
                                                     'path': path,
                                                   'similar_posts':similar_posts})

from .froms import  EmailPostForm
from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpResponse
def post_share(request, post_id):
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False
    if request.method == 'POST':
        # 通过request.POST提交过来的数据生成一个实例
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # return HttpResponse("进入")
            # is_valid()对引入的数据进行验证
            cd = form.cleaned_data
            #cleaned_data获取到的是一个字典，里面存放着验证通过后的数据
            post_url = request.build_absolute_uri(post.get_absolute_url())
            #通过get_absolute_url方法检索帖子的绝对路径
            #将该路径作为build_absolute_uri的输入内容，生成完整的url,包括路径和主机名
            # 发送激活邮箱
            # 邮件标题
            subject = '推荐你读这篇博客《{}》'.format(post.title)
            # 邮件正文
            message =  '在 {} 阅读博客《{}》 \n\n"{}"留言: {}'.format( post_url,post.title, cd['sender'], cd['message_board'])
            sender = settings.EMAIL_FROM  # 发件人
            receiver = [cd['send_email']]  # 收件人
            send_mail(subject, message, sender, receiver)
            sent = True#帖子发送后为True
    else:
        form = EmailPostForm()
    return render(request, 'blog/post/share.html', {'post': post,
                                                    'form': form,
                                                    'sent': sent})

from django.db.models import Q
def post_search(request):
    # path = request.path_info
    # context = {"path": path}
    # text=request.GET.get("text")
    # if text:
    #     post_s=Post.objects.filter(Q(title__icontains=text)|Q(body__icontains=text)&Q(status='published'))
    #     context["query"]=text
    #     context['count']=post_s.count()
    #     context["posts"]=post_s
    return render(request, 'blog/sousuo.html')